package ncme.auto.framework.core.mybatisplugin;

import ncme.auto.framework.core.dynamicDatasource.utils.ConvertUtil;
import ncme.auto.framework.core.exceptions.AutoException;
import ncme.auto.framework.core.exceptions.ExceptionEnum;
import ncme.auto.framework.core.utils.BeanUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Properties;

@Component
@Intercepts(
        {
                @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
        }
)
public class CreatorPlugin implements Interceptor {

    @Autowired
    private ConvertUtil convertUtil;

    @Value("${auto-framework-config.auto-fill-field.insert-username-fields}")
    private final String insertUsernameFields = "creator,editor";

    @Value("${auto-framework-config.auto-fill-field.update-username-fields}")
    private final String updateUsernameFields = "editor";

    /*intercept拦截：拦截目标对象的目标方法的执行*/
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        Integer userId = Integer.parseInt(request.getAttribute("userId").toString());
        String userName = request.getAttribute("userName").toString();

        //添加时需要填充当前时间的字段名
//        String[] insertTimeFields = new String[]{"creator", "editor"};
        String[] insertUsernameFields1 = insertUsernameFields.split(",");
        //更新时需要填充当前时间的字段名
//        String[] updateTimeFields = new String[]{"editor"};
        String[] updateUsernameFields1 = updateUsernameFields.split(",");

        try {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
            Object parameter = invocation.getArgs()[1];
            Object param1 = convertUtil.getRealParam(parameter);
            if (param1 != null) {
                List<Field> declaredFields = BeanUtil.getFieldsWithAnnotation(null, param1.getClass());
                if (sqlCommandType.name().equals("INSERT")) {
                    for (Field field : declaredFields) {
                        if (ArrayUtils.contains(insertUsernameFields1, field.getName())) {
                            BeanUtil.setFieldValue(param1, field.getName(), userName);
                        }
                    }
                } else if (sqlCommandType.name().equals("UPDATE")) {
                    for (Field field : declaredFields) {
                        if (ArrayUtils.contains(updateUsernameFields1, field.getName())) {
                            BeanUtil.setFieldValue(param1, field.getName(), userName);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new AutoException(ExceptionEnum.PLUGIN, "mybatis插件错误 caused by: " + e.getMessage());
        }
        return invocation.proceed();
    }

    /*plugin：包装目标对象（为目标对象创建一个代理对象）*/
    @Override
    public Object plugin(Object target) {
        Object wrap = Plugin.wrap(target, this);
        return wrap;
    }

    //将插件注册时的property属性设置进来
    @Override
    public void setProperties(Properties properties) {

    }

}
